// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import element, {Checkbox, Message, MessageBox, Option, Radio, Select, TabPane, Tabs, CheckboxGroup, RadioGroup} from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/less/style.less'
import * as filters from './filters'
import initPlugins from './utils/initPlugins'

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.use(Option)
Vue.use(Select)
Vue.use(element)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Checkbox)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(CheckboxGroup)

Vue.prototype.$message = Message
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm

Vue.config.productionTip = false

// 处理刷新的时候vuex被清空但是用户已经登录的情况
if (localStorage.token) {
  let datas = {
    id: window.localStorage.userId,
    token: window.localStorage.token
  }
  store.dispatch('recordUserInfo', datas)
}

// 登录中间验证
router.beforeEach((to, from, next) => {
  // 设置title
  document.title = to.meta.pageTitle || 'ldvue'

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.state.userInfo.token) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})
initPlugins()
